package com.reservation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reservation.common.BusinessException;
import com.reservation.dto.ExhibitionReservationDTO;
import com.reservation.entity.Exhibition;
import com.reservation.entity.ExhibitionReservation;
import com.reservation.entity.User;
import com.reservation.mapper.ExhibitionMapper;
import com.reservation.mapper.ExhibitionReservationMapper;
import com.reservation.mapper.UserMapper;
import com.reservation.service.ExhibitionReservationService;
import com.reservation.service.ExhibitionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 展览预约服务实现类
 */
@Service
public class ExhibitionReservationServiceImpl implements ExhibitionReservationService {

    @Autowired
    private ExhibitionReservationMapper exhibitionReservationMapper;

    @Autowired
    private ExhibitionMapper exhibitionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ExhibitionService exhibitionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExhibitionReservation createReservation(ExhibitionReservation reservation) {
        // 检查用户是否存在
        User user = userMapper.selectById(reservation.getUserId());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 检查展览是否存在
        Exhibition exhibition = exhibitionMapper.selectById(reservation.getExhibitionId());
        if (exhibition == null) {
            throw new BusinessException("展览不存在");
        }

        // 检查展览状态是否为进行中
        if (!"IN_PROGRESS".equals(exhibition.getStatus())) {
            throw new BusinessException("该展览当前不可预约");
        }

        // 检查预约日期是否在展览时间范围内
        LocalDate reservationDate = reservation.getReservationDate();
        if (reservationDate.isBefore(exhibition.getStartDate()) || reservationDate.isAfter(exhibition.getEndDate())) {
            throw new BusinessException("预约日期不在展览时间范围内");
        }

        // 检查当天预约人数是否已满
        if (!exhibitionService.checkDateAvailable(reservation.getExhibitionId(), reservationDate)) {
            throw new BusinessException("该日期预约人数已满");
        }

        // 检查用户是否已经预约过该展览的同一天
        if (checkUserHasReservation(reservation.getUserId(), reservation.getExhibitionId(), reservationDate)) {
            throw new BusinessException("您已预约过该展览的同一天");
        }

        // 设置预约状态和时间
        reservation.setStatus("PENDING");
        reservation.setCreateTime(LocalDateTime.now());
        reservation.setUpdateTime(LocalDateTime.now());

        // 保存预约信息
        exhibitionReservationMapper.insert(reservation);

        return reservation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExhibitionReservation updateReservationStatus(Long id, String status) {
        // 检查预约是否存在
        ExhibitionReservation reservation = exhibitionReservationMapper.selectById(id);
        if (reservation == null) {
            throw new BusinessException("预约不存在");
        }

        // 更新状态
        ExhibitionReservation updateReservation = new ExhibitionReservation();
        updateReservation.setId(id);
        updateReservation.setStatus(status);
        updateReservation.setUpdateTime(LocalDateTime.now());
        exhibitionReservationMapper.updateById(updateReservation);

        // 返回更新后的预约信息
        return exhibitionReservationMapper.selectById(id);
    }

    @Override
    public ExhibitionReservation getReservationById(Long id) {
        ExhibitionReservation reservation = exhibitionReservationMapper.selectById(id);
        if (reservation == null) {
            throw new BusinessException("预约不存在");
        }
        User user = userMapper.selectById(reservation.getUserId());
        Exhibition exhibition = exhibitionMapper.selectById(reservation.getExhibitionId());
        reservation.setUserName(user.getName());
        reservation.setExhibitionName(exhibition.getName());
        reservation.setPhone(user.getPhone());
        return reservation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelReservation(Long id) {
        // 检查预约是否存在
        ExhibitionReservation reservation = exhibitionReservationMapper.selectById(id);
        if (reservation == null) {
            throw new BusinessException("预约不存在");
        }

        // 检查预约状态是否可取消
        if ("CANCELED".equals(reservation.getStatus()) || "REJECTED".equals(reservation.getStatus())) {
            throw new BusinessException("该预约已取消或被拒绝");
        }

        // 更新状态为取消
        ExhibitionReservation updateReservation = new ExhibitionReservation();
        updateReservation.setId(id);
        updateReservation.setStatus("CANCELED");
        updateReservation.setUpdateTime(LocalDateTime.now());

        return exhibitionReservationMapper.updateById(updateReservation) > 0;
    }

    @Override
    public IPage<ExhibitionReservation> getUserReservations(Page<ExhibitionReservation> page, Long userId, String status) {
        LambdaQueryWrapper<ExhibitionReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExhibitionReservation::getUserId, userId);

        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(ExhibitionReservation::getStatus, status);
        }

        queryWrapper.orderByDesc(ExhibitionReservation::getCreateTime);

        Page<ExhibitionReservation> exhibitionReservationPage = exhibitionReservationMapper.selectPage(page, queryWrapper);
        List<ExhibitionReservation> reservationList = exhibitionReservationPage.getRecords();
        for (ExhibitionReservation reservation : reservationList) {
            Exhibition exhibition = exhibitionMapper.selectById(reservation.getExhibitionId());
            reservation.setExhibitionName(exhibition.getName());
        }
        return exhibitionReservationPage;
    }

    @Override
    public IPage<ExhibitionReservation> getExhibitionReservations(Page<ExhibitionReservation> page, Long exhibitionId, String status, LocalDate date) {
        LambdaQueryWrapper<ExhibitionReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExhibitionReservation::getExhibitionId, exhibitionId);

        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(ExhibitionReservation::getStatus, status);
        }

        if (date != null) {
            queryWrapper.eq(ExhibitionReservation::getReservationDate, date);
        }

        queryWrapper.orderByDesc(ExhibitionReservation::getCreateTime);

        return exhibitionReservationMapper.selectPage(page, queryWrapper);
    }

    @Override
    public IPage<ExhibitionReservation> getAllReservations(Page<ExhibitionReservation> page, String status) {
        LambdaQueryWrapper<ExhibitionReservation> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(ExhibitionReservation::getStatus, status);
        }

        queryWrapper.orderByDesc(ExhibitionReservation::getCreateTime);

        Page<ExhibitionReservation> exhibitionReservationPage = exhibitionReservationMapper.selectPage(page, queryWrapper);
        List<ExhibitionReservation> reservationList = exhibitionReservationPage.getRecords();
        for (ExhibitionReservation reservation : reservationList) {
            Exhibition exhibition = exhibitionMapper.selectById(reservation.getExhibitionId());
            User user = userMapper.selectById(reservation.getUserId());
            if(Objects.isNull(user)){
                continue;
            }
            //System.out.println(user);
            reservation.setUserName(user.getName());
            reservation.setExhibitionName(exhibition.getName());
        }
        return exhibitionReservationPage;
    }

    @Override
    public boolean checkUserHasReservation(Long userId, Long exhibitionId, LocalDate date) {
        LambdaQueryWrapper<ExhibitionReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExhibitionReservation::getUserId, userId);
        queryWrapper.eq(ExhibitionReservation::getExhibitionId, exhibitionId);
        queryWrapper.eq(ExhibitionReservation::getReservationDate, date);
        queryWrapper.in(ExhibitionReservation::getStatus, "PENDING", "APPROVED");

        return exhibitionReservationMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public List<ExhibitionReservation> getUserAllReservations(Long userId) {
        LambdaQueryWrapper<ExhibitionReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExhibitionReservation::getUserId, userId);
        queryWrapper.orderByDesc(ExhibitionReservation::getCreateTime);

        return exhibitionReservationMapper.selectList(queryWrapper);
    }

    @Override
    public List<ExhibitionReservation> getExhibitionAllReservations(Long exhibitionId) {
        LambdaQueryWrapper<ExhibitionReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExhibitionReservation::getExhibitionId, exhibitionId);
        queryWrapper.orderByDesc(ExhibitionReservation::getCreateTime);

        return exhibitionReservationMapper.selectList(queryWrapper);
    }

    @Override
    public boolean confirmReservation(Long id) {
        // 检查预约是否存在
        ExhibitionReservation reservation = exhibitionReservationMapper.selectById(id);
        if (reservation == null) {
            throw new BusinessException("预约不存在");
        }

        // 检查预约状态是否可取消
        if ("APPROVED".equals(reservation.getStatus()) || "CONFIRM".equals(reservation.getStatus())) {
            throw new BusinessException("该预约已确认");
        }

        // 更新状态为取消
        ExhibitionReservation updateReservation = new ExhibitionReservation();
        updateReservation.setId(id);
        updateReservation.setStatus("APPROVED");
        updateReservation.setUpdateTime(LocalDateTime.now());

        return exhibitionReservationMapper.updateById(updateReservation) > 0;
    }
}